<?
require_once('Geocoder/Geocoder.php');
//require_once('tarzan/tarzan.class.php');
ini_set('display_errors','off');

Class Craigslist{


	
	function __construct($qstr='',$catAbbreviation='aap'){
	
		$this->qstr = $_SERVER['QUERY_STRING'];
		//$this->server_vars = $_SERVER;
		//$this->nr_of_results;
		//$this->nr_of_pages;
		
		$this->city = "newyork";
		$this->borough = "mnh";
		$this->catAbbreviation = $catAbbreviation."/";
		$this->craigslist_base_url = "craigslist.org";
		$this->url_base = "http://".$this->city.".".$this->craigslist_base_url;
		$this->url = $this->url_base."/search/".$this->catAbbreviation.$this->borough."?".$this->qstr;
	 	//$this->sdb = $s = new AmazonSDB();
	
		//print_r($this);
	
	}
	
	function parse_all(){
	
	
	
	}
	

	
	
	function get_title_list($json='true'){
	//http://newyork.craigslist.org/search/aap/mnh/160?query=&minAsk=100&maxAsk=10000&bedrooms=1&neighborhood=160&addTwo=purrr&addThree=wooof&hasPic=1&s=100

		
		$r = new stdClass();
		$r->constructor = $this;
		$r->url = $this->url;
		$r->url_elements = parse_url($this->url, PHP_URL_PATH);
		$content = file_get_contents($r->url);		
		
		$r->ads_total = $this->ad_get_total($content);
		
		$rA = explode("<p> ",$content);
		
		array_shift($rA);
		array_pop($rA);
			$i=0;
			foreach($rA as $k=>$v){
			
				$r->ads[$k]['id'] = $this->ad_get_id($v);
				$r->ads[$k]['title'] = $this->ad_get_title($v);
				$r->ads[$k]['link'] = $this->ad_get_link($v);
				$r->ads[$k]['date'] = $this->ad_get_date($r->ads[$k]['title']);
				$r->ads[$k]['price'] = $this->ad_get_price($r->ads[$k]['title']);
				$r->ads[$k]['total_ads'] = $r->ads_total;
			 $i++;
			}
		if ($json) $r->json = json_encode($r->ads);
		return $r;		
	
	}
	
	function get_listing($q){}

	function fetch($json='true'){
	//http://newyork.craigslist.org/search/aap/mnh/160?query=&minAsk=100&maxAsk=10000&bedrooms=1&neighborhood=160&addTwo=purrr&addThree=wooof&hasPic=1&s=100

		
		$r = new stdClass();
		$r->constructor = $this;
		$r->url = $this->url;
		$r->url_elements = parse_url($this->url, PHP_URL_PATH);
		$content = file_get_contents($r->url);		
		
		$r->ads_total = $this->ad_get_total($content);
		
		$rA = explode("<p> ",$content);
		
		array_shift($rA);
		array_pop($rA);
			$i=0;
			foreach($rA as $k=>$v){
			
				$r->ads[$k]['id'] = $this->ad_get_id($v);
				
				//$details = '';
				//let's get it from db
				$time_start = $this->microtime_float();
				$details = $this->get_ad_from_simpledb($r->ads[$k]['id']);
				$time_end = $this->microtime_float();
				$time = $time_end - $time_start;
				$ttime += $time;
				
				if($details != ''){ //found in db (yey)

					$r->ads[$k]['title'] = $details['title'];
					$r->ads[$k]['link'] = $details['link'];
					$r->ads[$k]['date'] = $details['date'];
					$r->ads[$k]['price'] = $details['price'];
					$r->ads[$k]['location'] = $details['location'];
					$r->ads[$k]['latitude'] = $details['latitude'];
					$r->ads[$k]['longitude']= $details['longitude'];

					$r->ads[$k]['sdb'] ='yes';					
					
				}else{ //not found, get it from the link and put it to db
					
					
					$r->ads[$k]['title'] = $this->ad_get_title($v);
					$r->ads[$k]['link'] = $this->ad_get_link($v);
					
					$r->ads[$k]['date'] = $this->ad_get_date($r->ads[$k]['title']);
					$r->ads[$k]['price'] = $this->ad_get_price($r->ads[$k]['title']);
					
					$details = $this->ad_get_details($r->ads[$k]['link']);
					$r->ads[$k]['location'] = $details['location'];
					$r->ads[$k]['latitude'] = $details['latitude'];
					$r->ads[$k]['longitude']= $details['longitude'];
										
					//$r->ads[$k]['details'] = $this->ad_get_details($r->ads[$k]['link']);
					$put = $this->put_ad_to_simpledb($r->ads[$k]['id'], $r->ads[$k]);
		 			//$r->ads[$k]['simpledb_put_result'] = $put;
				}
				
				$r->ads[$k]['_seconds_passed_to_get_from_db'] = $time;
				
			 //if($i==5) break;
			 $i++;
			}
		$r->total_fetch_time = $ttime;
		if ($json) $r->json = json_encode($r->ads);
		return $r;		
	
	}

	function microtime_float(){
	    list($usec, $sec) = explode(" ", microtime());
	    return ((float)$usec + (float)$sec);
	}

	function ad_get_date($title){
		$a = explode("-",$title);
		$date = $a[0] .date("Y",time());
		return strtotime($date);		
	}
	
	function ad_get_price($title){
		$a = explode(" /",$title);
		$b = explode("- $",$a[0]);
		return $b[1];
	}
	
	function get_ad_from_simpledb($id){
		$xml = $this->sdb->get_attributes('craigslist',$id)->body->GetAttributesResult->Attribute;
		if(isset($xml[0])){
			$rA = array();
			 foreach($xml as $v){
			  foreach($v as $a => $b){
			 		if 	($a == 'Name') 	{$name = (string)$b;}
					else 				{$rA[$name] = (string)($b);}
			    }
			 }
		}
		return $rA;
	}
	
	function put_ad_to_simpledb($id,$array){
		$this->sdb->delete_attributes('craigslist',$id);
		return $this->sdb->put_attributes('craigslist',$id,$array,true);
		
	}
	
	function ad_get_coordinates($address){
		
		if (strlen($address) > 0) {
	        $geocoder = new Geocoder();
	        try {
	            $placemarks = $geocoder->lookup($address);
	        }
	        catch (Exception $ex) {
	            echo $ex->getMessage();
	            exit;
	        }
		}
		return $placemarks;
		
	}
	
	function ad_get_total($content){
		$a = explode('Found: ',$content);
		$b = explode(' Displaying: ',$a[1]);
		$total = $b[0];
		return $total;
		
		
	}
	
	function ad_get_title($ad){
		$a = explode("-</a>",$ad);
		array_pop($a);
		$r = preg_replace("/<.*>/","",$a[0]);
		//$r = preg_replace('/[^[:alnum:]]/','',$r);
		return $r;
	}
	
	function ad_get_link($ad){
		$a = explode('.html">',$ad);
		$b = explode('href="',$a[0]);
		$link = $this->url_base. $b[1].".html";
		return $link;
	}
	
	function ad_get_id($ad){
		$a = explode('.html">',$ad);
		$b = explode('/',$a[0]);
		$id = $b[count($b)-1];
		return $id;
	}
	
	function ad_get_location($content){
		
		$a = explode("<!-- CLTAG xstreet0=",$content);
		$b = explode('-->',$a[1]);
	  	
		$location = $b[0].",New York, NY, USA";

		if(strpos($location,"<")!==false) $location ='';
		
	return $location;
		
	}
	
	function ad_get_details($link,$json=true){
		$content = file_get_contents($link);
		$location = $this->ad_get_location($content);
		$placemarks = $this->ad_get_coordinates($location);	
		$r=null;
		if(isset($placemarks[0])){
			$latitude =  $placemarks[0]->getPoint()->getLatitude();
			$longitude = $placemarks[0]->getPoint()->getLongitude();
			$r=  array('location'=>$location,'latitude'=>$latitude,'longitude'=>$longitude);
		}
	  
		//$c = explode('<a href="mailto:',$content);
		//$d = explode(')">',$c[1]);
		//$r->mail_to = html_entity_decode($d[0].")");
	  
		//$e = explode('<div id="userbody">',$content);
		//$f = explode('</div>',$e[1]);
		//$r->body = $f[0];
	  if ($json) $r = json_encode($r);
	
	//return $content;
	
	return $r;
	
	}
	
	function convert_array_to_object($arr){
			$obj = new stdClass();
			$i = 0;
			foreach ($arr as $k=>$v){
			if($v!=""){
				$obj->$k = $v;
				$i++;}
			}
			return $obj;
	}
		
}
?>